package com.hgy.commonsale.service.impl;

import java.util.List;
import org.geln.web.hibernate.BaseHibernateService;
import org.geln.web.status.Status;
import com.hgy.commonsale.service.AdminManagerService;
import com.hgy.commonsale.user.domain.Admin;

public class AdminManagerServiceImpl extends BaseHibernateService implements AdminManagerService{
	
	/**
	 * query for admin by admin's user name
	 * @param adminName
	 * @return
	 */
	public Admin getAdminByAdminName(String adminName){
		String queryString="from Admin where adminUserName=? ";
		List<Admin> list=getHibernateTemplate().find(queryString, new String[]{adminName});
		if(list!=null &&list.size()==1){
			return (Admin)list.get(0);
		}
		return null;
	}
	
	public Admin getAdminById(String id) {
		List<Admin> list =findNameQuery("getUserById", new String[] { id }, null);
		if (list != null && list.size() == 1) {
			return list.get(0);
		}
		return null;
	}

	public Status saveOrUpdate(Admin admin) {
		if (admin == null)
			return Status.FAILED_FOR_NULL;
		if (admin.getAdminID() == null || admin.getAdminID().trim().length() == 0) {
			return save(admin);
		} else {
			return update(admin);
		}

	}

	protected Status update(Admin admin) {
		String userId = admin.getAdminID();
		getHibernateTemplate().evict(admin);
		Admin adminDB =this.getAdminById(userId);
		if (adminDB == null) {
			return Status.FAILED;
		} else {
			getHibernateTemplate().update(adminDB);
			return Status.SUCCESS;
		}
	}

	protected Status save(Admin admin) {
		if (exists(admin.getAdminID()))
			return Status.FAILED;
		
		getHibernateTemplate().save(admin);
		return Status.SUCCESS;
	}

	public boolean exists(String adminName) {
		Admin admin =this.getAdminByAdminName(adminName);
		if (admin != null)
			return true;
		return false;
	}
	
}
